package cn.pconline.autoclub.web.admin;

import cn.pconline.autoclub.entity.ClubAwardRecord;
import cn.pconline.autoclub.entity.ClubLevel;
import cn.pconline.autoclub.entity.Theme;
import cn.pconline.autoclub.service.ClubAwardRecordService;
import cn.pconline.autoclub.service.ClubLevelService;
import cn.pconline.autoclub.service.ClubService;
import cn.pconline.autoclub.service.ThemeService;
import cn.pconline.autoclub.util.Pager;
import cn.pconline.autoclub.util.club.ClubUpgradeRecord;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang.StringUtils;
import org.gelivable.log.GeliLogFacade;
import org.gelivable.web.Env;
import org.gelivable.web.EnvUtils;
import org.gelivable.web.HttpMethod;
import org.gelivable.webmvc.JSONBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping("/admin")
public class ClubAwardRecordController {

    @Autowired
    private ClubAwardRecordService clubAwardRecordService;
    @Autowired
    private ClubLevelService clubLevelService;
    @Autowired
    private ClubService clubService;
    @Autowired
    private ThemeService themeService;
    private static final Logger log = LoggerFactory.getLogger(ClubAwardRecordController.class);

    private void successMsg(String msg, String navTabId, HttpServletResponse resp) {
        try {
            resp.setCharacterEncoding("UTF-8");
            resp.getWriter().println(new JSONBuilder()
                    .put("statusCode", 200)
                    .put("message", msg)
                    .put("navTabId", navTabId)
                    .toString());
        } catch (IOException ex) {
            log.error("set successMsg fail!", ex);
        }
    }

    private void errorMsg(String msg, HttpServletResponse resp) {
        try {
            resp.setCharacterEncoding("UTF-8");
            resp.getWriter().println(new JSONBuilder()
                    .put("statusCode", 300)
                    .put("message", msg)
                    .toString());
        } catch (IOException ex) {
            log.error("set errorMsg fail!", ex);
        }
    }

    /**
     * 领奖记录
     *
     * @param req
     * @param resp
     * @return
     */
    @RequestMapping(value = "/club/awardRecord.do")
    public String awardRecord(HttpServletRequest req, HttpServletResponse resp) {
        Env env = EnvUtils.getEnv();
        String orderField = env.param("orderField", "club_award_record_id");
        String orderDirection = env.param("orderDirection", "asc");
        int pageNum = env.paramInt("pageNum", 1);
        int pageSize = env.paramInt("pageSize", 20);
        String startStr = req.getParameter("begin");
        String endStr = req.getParameter("end");
        Date begin = env.parseDate(StringUtils.defaultIfBlank(startStr, "1970-01-01 00:00:00"));
        Date end = env.parseDate(StringUtils.defaultIfBlank(endStr, "2970-01-01 00:00:00"));
        String clubName = env.param("clubName", "");
        int levelId = env.paramInt("levelName", 0);

        Pager<ClubAwardRecord> pager = clubAwardRecordService.pager(clubName, levelId, begin, end, pageNum, pageSize, orderField, orderDirection);
        if (pager.getResultList() != null && (!pager.getResultList().isEmpty())) {
            for (ClubAwardRecord c : pager.getResultList()) {
                c.setLevelName(clubLevelService.getClubLevelNameById(c.getLevelId()));
                c.setClubName(clubService.getClub(c.getClubId()).getName());
            }
        }

        req.setAttribute("pager", pager);
        req.setAttribute("orderField", orderField);
        req.setAttribute("orderDirection", orderDirection);
        req.setAttribute("STATUS_NO", ClubAwardRecord.STATUS_NO);
        req.setAttribute("STATUS_YES", ClubAwardRecord.STATUS_YES);
        req.setAttribute("RECEIVED_NO", ClubAwardRecord.RECEIVED_NO);
        req.setAttribute("RECEIVED_YES", ClubAwardRecord.STATUS_YES);

        return "admin/club/awardRecord";
    }

    /**
     * 修改发货状态
     *
     * @param req
     * @param resp
     * @return
     */
    @RequestMapping(value = "/club/updateStatus.do")
    public String updateStatus(HttpServletRequest req, HttpServletResponse resp) {
        Env env = EnvUtils.getEnv();
        GeliLogFacade.log();
        HttpMethod method = env.getHttpMethod();
        if (!method.equals(HttpMethod.POST)) {
            errorMsg("非法请求", resp);
            return null;
        }
        long clubAwardRecordId = env.paramLong("id", 0);
        ClubAwardRecord clubAwardRecord = clubAwardRecordService.getById(clubAwardRecordId);

        if (clubAwardRecord == null) {
            log.error("修改发货状态失败，失败原因：ClubAwardRecord为空(id=" + clubAwardRecordId + ")");
            this.errorMsg("数据异常，修改失败", resp);
            return null;
        }
        clubAwardRecord.setStatus(ClubAwardRecord.STATUS_YES);
        clubAwardRecordService.update(clubAwardRecord);

        this.successMsg("修改成功", "award-record", resp);
        return null;
    }

    /**
     * 车友会升级列表
     *
     * @param req
     * @param resp
     * @return
     */
    @RequestMapping(value = "/club/upgradeClubList.do")
    public String upgradeClubList(HttpServletRequest req, HttpServletResponse resp) {
        Env env = EnvUtils.getEnv();
        int pageNum = env.paramInt("pageNum", 1);
        int pageSize = env.paramInt("pageSize", 20);
        int startLevel = env.paramInt("startLevel", -1);
        String orderDirection = env.param("orderDirection", "desc");
        String startStr = req.getParameter("begin");
        String endStr = req.getParameter("end");
        Date begin = env.parseDate(StringUtils.defaultIfBlank(startStr, "1970-01-01 00:00:00"));
        Date end = env.parseDate(StringUtils.defaultIfBlank(endStr, "2970-01-01 00:00:00"));
        String brand = env.param("brand","").trim();
        String series = env.param("series","").trim();
        int theme = env.paramInt("theme",0);
        String area = env.param("area","").trim();
        
        Pager<ClubUpgradeRecord> pager = clubAwardRecordService.pager(brand, series, theme, area, begin, end, startLevel, orderDirection.equals("desc"), pageNum, pageSize);
        
        List<ClubLevel> levels = clubLevelService.getAllLevels();
        
        List<Theme> themes = themeService.listAllThemes();
        req.setAttribute("levels", levels);
        req.setAttribute("pager", pager);
        req.setAttribute("themes", themes);
        req.setAttribute("theme", theme);
        req.setAttribute("startLevel", startLevel);
        req.setAttribute("orderDirection", orderDirection);
        return "admin/club/clubUpgradeRecord";
    }
}
